package JavaUtils.test_socket.demo03;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
 
/**
 * @Description:     DUP提供者，用于提供服务
 * @Author:          nicecloud
 * @CreateDate:      2019/6/29 22:55
 * @Version:         1.0
 */
public class UDPProvider {
    public static void main(String[] args) throws IOException {
        System.out.println("UDPProvider started.");
        // 作为接收者，指定一个端口用于数据接收
        DatagramSocket ds = new DatagramSocket(20000);
 
        // 构建接收实体
        final byte[] buf = new byte[512];
        DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
        // 接收
        ds.receive(receivePacket);
 
        // 打印接收到的信息与发送者的信息
        // 发送者的IP地址
        String ip = receivePacket.getAddress().getHostAddress();
        int port = receivePacket.getPort();
        int dataLen = receivePacket.getLength();
        String data = new String(receivePacket.getData(), 0, dataLen);
        System.out.println("UDPProvider receive from ip:" + ip + "\tport:" + port + "\tdata:" + data);
 
        // 构建一份回送数据
        String responseData = "Receive data with len:" + dataLen;
        byte[] responDataBytes = responseData.getBytes();
        // 直接根据发送者构建一份回送信息
        DatagramPacket responsePacket = new DatagramPacket(responDataBytes,
                responDataBytes.length,
                receivePacket.getAddress(),
                receivePacket.getPort());
        ds.send(responsePacket);
 
        // 完成
        System.out.println("UDPProvider Finished.");
        ds.close();
 
 
    }
}